import re
import subprocess


def sync_requirements_to_poetry():
    # 1. 读取requirements.txt中的依赖（过滤注释和空行，提取包名和版本）
    deps = []
    with open("requirements.txt", "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            # 跳过注释、空行和URL形式的依赖（如git+https://...）
            if not line or line.startswith("#") or "git+" in line:
                continue
            # 匹配 "包名==版本号" 格式（兼容带额外约束的行）
            match = re.match(r"^([a-zA-Z0-9_-]+)==([0-9a-zA-Z.+-]+)", line)
            if match:
                pkg_name, pkg_version = match.groups()
                deps.append(f"{pkg_name}=={pkg_version}")

    if not deps:
        return

    # 2. 批量调用Poetry添加依赖（显示实时输出）
    try:
        result = subprocess.run(
            ["poetry", "add", "--quiet", "--no-interaction", "--no-ansi"] + deps,
            check=False,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        )
    except subprocess.CalledProcessError as e:
        return
    except FileNotFoundError:
        return


if __name__ == "__main__":
    sync_requirements_to_poetry()
